package com.sinodata.bsm.cicp.collector.file;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;

import com.sinodata.bsm.cicp.collector.Collector;
import com.sinodata.bsm.cicp.exception.CollectorException;
import com.sinodata.bsm.cicp.util.CommandReader;
import com.sinodata.bsm.cicp.util.ProtocolParameterUtil;
import com.sinodata.bsm.common.vo.ProtocolParameter;
import com.sinodata.bsm.common.vo.ResPropertyValue;

public class FileScheduleSimls extends Collector {
    private static Logger logger = Logger.getLogger(com.sinodata.bsm.cicp.collector.file.FileScheduleSimls.class);

    /**
     * 实现对一个文件夹下的所有文件的修改时间的获取，取出最近修改的那个文件的文件名、修改时间、采集时间
     * @param resourceAttributes ResAttributeValValue[]
     * @param ip String
     * @return List
     * @throws CollectorException
     */

    @Override
    public List<ResPropertyValue> collect(String ip) throws CollectorException {
        if (this.getParamMeta() == null || this.getParamMeta().length < 2) {
            logger.error("parameter is wrong，failed to collecte");
            return null;
        }
        String[] propMetas = getPropMeta();
        ResPropertyValue propertyValueX = new ResPropertyValue();
        ResPropertyValue.PropValue[] propValues = new ResPropertyValue.PropValue[propMetas.length];

        String path = this.getParamMap().get("FileCatalog").trim();//文件目录
        String fileName = this.getParamMap().get("FileFormat").trim();//文件格式
        BufferedReader reader = null;
        List<ResPropertyValue> result = new ArrayList<ResPropertyValue>();
        ProtocolParameter protocolParameter = ProtocolParameterUtil.getHostValue(ip);
        String fileDir = protocolParameter.getUrl();
        String shell = getCommandShell(path, fileName, fileDir);
        try {
            reader = CommandReader.getReader(ip, shell, (int) this.interval, 0);
            if (reader == null) {
                logger.error("failed to read file");
                return null;
            }
            String readLine = reader.readLine();

            if (readLine == null) {
                propValues[0] = ResPropertyValue.createPropValue("N/A", propMetas[0]);
                propValues[3] = ResPropertyValue.createPropValue("0", propMetas[3]);
                propValues[1] = ResPropertyValue.createPropValue("", propMetas[1]);
                propValues[2] = ResPropertyValue.createPropValue("", propMetas[2]);
                propertyValueX.setValues(propValues);
                result.add(propertyValueX);
                return result;
            }

            if (readLine.trim().equals("命令参数不对")) {
                return null;
            }
            readLine = readLine.trim();
            String[] tmp = readLine.split("\t");
            if (tmp.length != 3) {
                return null;
            }
            String arrt0 = null;
            if (tmp[0].indexOf('/') != -1) {
                arrt0 = tmp[0].substring(tmp[0].lastIndexOf('/') + 1);
            } else {
                arrt0 = tmp[0];
            }
            String arr1 = "" + Integer.parseInt(tmp[1].trim());
            String arr2 = new Date(getDateMillis(tmp[2].trim())).getTime() + "";
            String arr3 = new Date(getRemoteCurrentTimeMillis(ip)).getTime() + "";
            propValues[0] = ResPropertyValue.createPropValue(arrt0, propMetas[0]);
            propValues[3] = ResPropertyValue.createPropValue(arr1, propMetas[3]);
            propValues[1] = ResPropertyValue.createPropValue(arr2, propMetas[1]);
            propValues[2] = ResPropertyValue.createPropValue(arr3, propMetas[2]);
            propertyValueX.setValues(propValues);
            result.add(propertyValueX);
            return result;
        } catch (IOException e) {
            logger.error("read file error", e);
            throw new CollectorException(e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (java.io.IOException e) {
                    logger.error("read file error", e);
                    throw new CollectorException(e);
                }
            }
        }
    }

    private long getRemoteCurrentTimeMillis(String ip) throws CollectorException {
        BufferedReader reader = null;
        try {
            reader = CommandReader.getReader(ip, "date +%Y%m%d%H%M%S", (int) this.interval, 0);
            String readLine = reader.readLine();
            if (readLine != null) {
                return getDateMillis(readLine);
            }
        } catch (Exception e) {
            logger.error("occur error when call " + this.getClass().getName() + "getRemoteCurrentTimeMillis", e);
            throw new CollectorException(e);
        }
        return System.currentTimeMillis();
    }

    private String getCommandShell(String path, String fileName, String filterDir) {
        path = path.trim();
        if (!path.endsWith("/")) {
            path += "/";
        }
        fileName = path + fileName;
        StringBuffer buffer = new StringBuffer();
        if (filterDir != null && !filterDir.equals("")) {
            filterDir = filterDir.trim();
            if (!filterDir.endsWith("/")) {
                filterDir += "/";
            }
            buffer.append(filterDir);
        }
        buffer.append("simls ").append("-l ");
        buffer.append(fileName);
        return buffer.toString();
    }

    private long getDateMillis(String date) {
        Calendar calendar = Calendar.getInstance();
        int year = Integer.parseInt(date.substring(0, 4));
        int month = Integer.parseInt(date.substring(4, 6)) - 1;
        int day = Integer.parseInt(date.substring(6, 8));
        int hour = Integer.parseInt(date.substring(8, 10));
        int minute = Integer.parseInt(date.substring(10, 12));
        int second = Integer.parseInt(date.substring(12));
        calendar.set(year, month, day, hour, minute, second);
        int milliSecond = calendar.get(Calendar.MILLISECOND);
        return calendar.getTimeInMillis() - milliSecond;
    }

    @Override
    public String[] getParamMeta() {
        //        return new String[] { "文件目录", "文件格式" };
        return new String[] { "FileCatalog", "FileFormat" };
    }

    @Override
    public String[] getPropMeta() {
        //        return new String[] { "fileName", "processTime", "collectTime", "fileSize" };
        return new String[] { "$1", "$2", "$3", "$4" };
    }

}
